package com.my.dao.impl;

import java.math.BigInteger;
import java.util.List;

import com.my.bean.Part;
import com.my.dao.IBaseDAO;
import com.my.dao.PartDAO;

public class PartDAOImpl implements PartDAO {
	private IBaseDAO<Part> basedao;

	public void setBasedao(IBaseDAO<Part> basedao) {
		this.basedao = basedao;
	}

	@Override
	public boolean addPart(Part part) throws Exception {
		if (this.checkPart(part)) {
			return basedao.add(part);
		}
		return false;
	}

	@Override
	public boolean editPart(Part part) throws Exception {
		if (this.checkPart(part)) {
			return basedao.edit(part);
		}
		return false;
	}

	@Override
	public Part getPartById(Class<Part> c, Integer id) throws Exception {
		return basedao.getById(c, id);
	}

	@Override
	public boolean removePart(Integer id) throws Exception {
		Part part = basedao.getById(Part.class, id);
		if (part != null) {
			basedao.remove(part);
		}
		return false;
	}

	@Override
	public BigInteger getTotalPartRecords() throws Exception {
		String sql = "select count(part_id) from info_part";
		return basedao.getTotalRecords(sql);
	}

	@Override
	public List<Part> getAllPartByPage(int pageindex, int pagesize)
			throws Exception {
		String hql = "from Part";
		return basedao.getAllEntityByPage(hql, pageindex, pagesize);
	}

	@Override
	public BigInteger searchTotalPartRecords(Part part) throws Exception {
		String sql = "select count(part_id) from info_part where part_name like ?";
		String item1 = part.getName() + "%";
		return basedao.getTotalRecords(sql, item1);
	}

	@Override
	public List<Part> searchPartByPage(int pageindex, int pagesize, Part part)
			throws Exception {
		String hql = "from Part as p where p.name like ?";
		String item1 = part.getName() + "%";
		return basedao.getAllEntityByPage(hql, pageindex, pagesize, item1);
	}

	boolean checkPart(Part part) {
		if (part == null || part.getName() == null || part.getName().isEmpty()) {
			return false;
		} else {
			return true;
		}
	}

	@Override
	public boolean isExist(String name) {
		if (name.isEmpty()) {
			return false;
		}
		String hql = "from Part as a where a.name=?";
		return basedao.isExist(hql, name);
	}

}
